<template>
  <div class="search-suggestion">
    <van-cell
      v-for="(sug, index) in suggestions"
      :key="index"
      @click="$emit('search', sug)"
      icon="search"
    >
      <span slot="title" v-html="highlight(sug)"></span>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search'
//  按需加载
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  data () {
    return {
      suggestions: [],
      htmlStr: '<span style="color: red"></span>'
    }
  },
  props: {
    searchText: {
      type: String,
      require: true
    }
  },
  //  检测
  watch: {
    searchText: {
      // searchText 发生变化是 调用handler函数
      handler: debounce(function (value) {
        this.loadSearchSuggestions(value)
      }, 200),
      immediate: true // 侦听后立马调用
    }
  },
  methods: {
    async loadSearchSuggestions (q) {
      try {
        const { data } = await getSearchSuggestion(q)
        this.suggestions = data.data.options
      } catch (err) {
        this.$toast('失败')
      }
    },
    highlight (sug) {
      if (!sug) return
      const highlightStr = `<span class="active">${this.searchText}</span>`

      // RegExp正则表达式构造函数
      const reg = new RegExp(this.searchText, 'gi')
      return sug.replace(reg, highlightStr)
    }
  }
}
</script>

<style scoped lang="less">
.search-suggestion {
  /deep/ span.active {
    color: #3296fa;
  }
}
</style>
